package com.htgraph.flash;

import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxIGraphModel;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Dong Shufeng
 *         Date: 2010-11-25
 */
public abstract class Flasher {

    protected List<mxCell> toFlashCells;
    protected boolean newState = false;
    protected Map<mxCell, String> originalStyle;
    protected mxIGraphModel model;
    private boolean editState = false;

    protected Flasher(mxIGraphModel model) {
        this();
        this.model = model;
    }

    protected Flasher() {
        toFlashCells = new ArrayList<mxCell>();
        originalStyle = new HashMap<mxCell, String>();
    }

    public void setToFlashCells(List<mxCell> toFlashCells) {
        this.toFlashCells = toFlashCells;
        originalStyle = new HashMap<mxCell, String>(toFlashCells.size());
        for(mxCell cell : toFlashCells)
            originalStyle.put(cell, cell.getStyle());
    }

    synchronized public void addToFlash(mxCell cell) {
        toFlashCells.add(cell);
        originalStyle.put(cell, cell.getStyle());
    }

    synchronized public void clear() {
        if(toFlashCells == null)
            return;
        if(model == null)
            return;
        try {
            model.beginUpdate();
            for(mxCell cell : toFlashCells)
                model.setStyle(cell, originalStyle.get(cell));
        } finally {
            newState = !newState;
            toFlashCells.clear();
            originalStyle.clear();
            model.endUpdate();
        }
    }

    public mxIGraphModel getModel() {
        return model;
    }

    public void setModel(mxIGraphModel model) {
        this.model = model;
    }

     public synchronized void flash() {
        if (toFlashCells == null)
            return;
         if(model == null)
             return;
        try {
            model.beginUpdate();
            doFlash();
        } finally {
            model.endUpdate();
            newState = !newState;
        }
    }

    abstract public void doFlash();

    public static Flasher getDoNothingFlasher() {
        return new Flasher() {
            public void doFlash() {
            }
        };
    }

    public void setEditState(boolean editState) {
        this.editState = editState;
    }

    public boolean getEditState() {
        return editState;
    }
}


